<template>
	<div class="merak-container-has-aside" id="zy_20240320002">
		<div class="merak-aside">
			 <treeNode @node-change="nodeChange" :defTreeValue="org_id"></treeNode>
		</div>
		<div v-waterMarker class="merak-card merak-container-has-search">
			<searchBar close-plan close-advanced custom-class="searchHeaderDaily" :placeholder="$t('clockingIn_daily.search_keyword')"  ref="searchbar" @search-event="searchBarPost">
				<template #header>
					<el-select style="width: 200px;" v-model="state.thisPageDate.office_location_id" value-key="key" clearable :placeholder="$t('clockingIn_daily.office_location')">
						<el-option v-for="oItem in workLocationArr" :key="oItem.value" :label="oItem.label"
							:value="oItem.value" />
					</el-select>
					<el-date-picker
						style="width:100px;margin-left:10px;" 
						:editable="false"
						v-model="state.thisPageDate.date"
						type="month"
						:format="format"
						value-format="YYYY-MM"
						:clearable="false"
						class="dateBox"
						@change="editDate"
					/>
					
				</template>
			</searchBar>
			<div class="merak-table-wrapper clockingInTable">
				<MerakXTable v-bind="tablePayload" :batch-click="handleBatchClick" :handler-click="handleHanderClick" :query-data="queryData">
					<!-- <template #employee_details_head="{ column }">
						<div class="employee_details_head">
							{{column.title}}
						</div>
					</template> -->
					<template #employee_details="{ row }">
						<div class="user_box">
							<!-- <img :src="row.avatar"/> -->
							<div class="user_name">{{row.employee_name}}</div>
						</div> 
					</template>
					<template #day_box="{ row,column }">
						<!-- <div @click="showData(row,column)">点击块儿</div> -->
						<div class="calendarDayBox" v-if="row[column.field]?.status != -1">
							<div v-if="row[column.field]?.out !== ''">
								<div class="workTime leave"><div class="after"></div>{{$t('clockingIn_daily.go_out')}}：{{row[column.field].out}}</div>
							</div>
							<div v-else-if="row[column.field]?.on_status == 0 && row[column.field]?.off_status == 0">
								<div class="workTime beOnDuty"><div class="after"></div>{{$t('clockingIn_daily.working')}}：{{row[column.field].on}}</div>
								<div class="workTime offDuty"><div class="after"></div>{{$t('clockingIn_daily.off_duty')}}：{{row[column.field].off}}</div>
							</div>
							<div v-else-if="row[column.field]?.on_status == 2 && row[column.field]?.off_status == 2">
								<div class="workTime absenteeism"><div class="after"></div>{{$t('clockingIn_daily.absenteeism')}}</div>
							</div>
							<div v-else-if="row[column.field]?.on_status == 0 && row[column.field]?.off_status == 2">
								<div class="workTime beOnDuty"><div class="after"></div>{{$t('clockingIn_daily.working')}}：{{row[column.field].on}}</div>
								<div class="workTime absenteeism"><div class="after"></div>{{$t('clockingIn_daily.absenteeism')}}</div>
							</div>
							<div v-else-if="row[column.field]?.on_status == 2 && row[column.field]?.off_status == 0">
								<div class="workTime absenteeism"><div class="after"></div>{{$t('clockingIn_daily.absenteeism')}}</div>
								<div class="workTime offDuty"><div class="after"></div>{{$t('clockingIn_daily.off_duty')}}：{{row[column.field].off}}</div>
							</div>
							<el-popover v-else :show-arrow="false" :offset="-50" width="350" placement="right-start">
								<template #reference>
									<div v-if="row[column.field]?.on_status === row[column.field]?.off_status">
										<div v-if="row[column.field]?.on_status === 1">
											<div v-if="row[column.field]?.leave.length == 1">
												<div class="workTime leave headIcon" :style="{'color':row[column.field]?.leave[0].color}"><div class="after" :style="{'background-color':row[column.field]?.leave[0].color}"></div>{{row[column.field]?.leave[0]?.type}}</div>
											</div>
											<div v-else-if="row[column.field]?.leave.length == 2">
												<div class="workTime leave headIcon" :style="{'color':row[column.field]?.leave[0].color}"><div class="after" :style="{'background-color':row[column.field]?.leave[0].color}"></div>{{row[column.field]?.leave[0]?.type}}</div>
												<div class="workTime leave headIcon" :style="{'color':row[column.field]?.leave[1].color}"><div class="after" :style="{'background-color':row[column.field]?.leave[1].color}"></div>{{row[column.field]?.leave[1]?.type}}</div>
											</div>
										</div>
									</div>
									<div v-else>
										<div>
											<div v-if="row[column.field]?.on_status == 0">
												<div class="workTime beOnDuty"><div class="after"></div>{{$t('clockingIn_daily.working')}}：{{row[column.field].on}}</div>
											</div>
											<div v-else-if="row[column.field]?.on_status == 1">
												<div class="workTime leave headIcon" :style="{'color':row[column.field]?.leave[0]?.color}"><div class="after" :style="{'background-color':row[column.field]?.leave[0]?.color}"></div>{{row[column.field]?.leave[0]?.type}}</div>
											</div>
											<div v-else-if="row[column.field]?.on_status == 2">
												<div class="workTime absenteeism"><div class="after"></div>{{$t('clockingIn_daily.absenteeism')}}</div>
											</div>
											<div v-else-if="row[column.field]?.on_status == 3">
												<div class="workTime beLate headIcon"><div class="after"></div>{{$t('clockingIn_daily.be_late')}}</div>
											</div>
										</div>
										<div>
											<div v-if="row[column.field]?.off_status == 0">
												<div class="workTime beOnDuty"><div class="after"></div>{{$t('clockingIn_daily.off_duty')}}：{{row[column.field].off}}</div>
											</div>
											<div v-else-if="row[column.field]?.off_status == 1">
												<div class="workTime leave headIcon" :style="{'color':row[column.field]?.leave[0]?.color}"><div class="after" :style="{'background-color':row[column.field]?.leave[0]?.color}"></div>{{row[column.field]?.leave[0]?.type}}</div>
											</div>
											<div v-else-if="row[column.field]?.off_status == 2">
												<div class="workTime absenteeism"><div class="after"></div>{{$t('clockingIn_daily.absenteeism')}}</div>
											</div>
											<div v-else-if="row[column.field]?.off_status == 3">
												<div class="workTime leaveEarly headIcon"><div class="after"></div>{{$t('clockingIn_daily.leave_early')}}</div>
											</div>
										</div>
									</div>
								</template>
								<div class="calendar_card">
									<div v-if="row[column.field]?.on_status == row[column.field]?.off_status">
										<div v-if="row[column.field]?.on_status == 1">
											<div v-if="row[column.field]?.leave.length == 1">
												<div class="calendar_text title">{{row[column.field].leave[0].title}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_type')}}：{{row[column.field]?.leave[0]?.type}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_time')}}：{{row[column.field]?.leave[0]?.begin}}~{{row[column.field]?.leave[0]?.end}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_reason')}}：{{row[column.field]?.leave[0]?.reason}}</div>
												<div class="flx-align-center calendar_text">
													<div>{{$t('clockingIn_daily.approver')}}：</div>
													<div v-for="(item,index) in row[column.field]?.leave[0]?.approver" :key="index">{{item?.employee_name}}</div>
												</div>
											</div>
											<div v-else="row[column.field]?.leave.length == 2">
												<div class="calendar_text title">{{row[column.field].leave[0].title}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_type')}}：{{row[column.field]?.leave[0]?.type}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_time')}}：{{row[column.field]?.leave[0]?.begin}}~{{row[column.field]?.leave[0]?.end}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_reason')}}：{{row[column.field]?.leave[0]?.reason}}</div>
												<div class="flx-align-center calendar_text">
													<div>{{$t('clockingIn_daily.approver')}}：</div>
													<div v-for="(item,index) in row[column.field]?.leave[0]?.approver" :key="index">{{item?.employee_name}}</div>
												</div>
												<div class="calendar_text title">{{row[column.field].leave[1].title}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_type')}}：{{row[column.field]?.leave[1]?.type}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_time')}}：{{row[column.field]?.leave[1]?.begin}}~{{row[column.field]?.leave[1]?.end}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_reason')}}：{{row[column.field]?.leave[1]?.reason}}</div>
												<div class="flx-align-center calendar_text">
													<div>{{$t('clockingIn_daily.approver')}}：</div>
													<div v-for="(item,index) in row[column.field]?.leave[1].approver" :key="index">{{item?.employee_name}}</div>
												</div>
											</div>
										</div>
									</div>
									<div v-else>
										<div>
											<div v-if="row[column.field]?.on_status == 1">
												<div class="calendar_text title">{{row[column.field]?.leave[0].title}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_type')}}：{{row[column.field]?.leave[0].type}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_time')}}：{{row[column.field]?.leave[0].begin}}~{{row[column.field]?.leave[0].end}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_reason')}}：{{row[column.field]?.leave[0].reason}}</div>
												<div class="flx-align-center calendar_text">
													<div>{{$t('clockingIn_daily.approver')}}：</div>
													<div v-for="(item,index) in row[column.field]?.leave[0].approver" :key="index">{{item?.employee_name}}</div>
												</div>
											</div>
											<div v-else-if="row[column.field]?.on_status == 3">
												<div class="calendar_text">{{$t('clockingIn_daily.clocking_time')}}：{{row[column.field]?.on}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.be_late')}}：{{convertSecondsToHMS(row[column.field]?.late_second)}}</div>
											</div>
										</div>
										<div>
											<div v-if="row[column.field]?.off_status == 1">
												<div class="calendar_text title">{{row[column.field].leave[0].title}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_type')}}：{{row[column.field]?.leave[0]?.type}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_time')}}：{{row[column.field]?.leave[0]?.begin}}~{{row[column.field]?.leave[0]?.end}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_reason')}}：{{row[column.field]?.leave[0]?.reason}}</div>
												<div class="flx-align-center calendar_text">
													<div>{{$t('clockingIn_daily.approver')}}：</div>
													<div v-for="(item,index) in row[column.field]?.leave[0]?.approver" :key="index">{{item?.employee_name}}</div>
												</div>
											</div>
											<div v-else-if="row[column.field]?.off_status == 3">
												<div class="calendar_text">{{$t('clockingIn_daily.clocking_time')}}：{{row[column.field]?.off}}</div>
												<div class="calendar_text">{{$t('clockingIn_daily.leave_early')}}：{{convertSecondsToHMS(row[column.field]?.before_quit_second)}}</div>
											</div>
										</div>
									</div>
								</div>
							</el-popover>
							
						</div>
					</template>
				</MerakXTable>
			</div>
			
		</div>
	</div>
</template>

<!-- render 函数需要设置为 jsx 语法 -->
<script setup lang="tsx" name="attendanceDetail">
	import {
		reactive,
		computed,
		watch,
		onMounted,
		ref,
		getCurrentInstance
	} from "vue";
	import {
		ElButton,
		ElPopover
	} from "element-plus";
	import treeNode from '@/views/personalManagement/a-components/oragnizationTree/index.vue';
	import TreeFilter from "@/components/TreeFilter/index.vue";
	import searchBar from "@/components/SearchBar";
	import MerakXTable, {
		MerakXTableColumn,
		MerakXTableInstance,
		MerakXTableProps
	} from "@/components/MerakXTable";
	import useLoading from "@/hooks/useLoading";
	import router from "@/routers";
	import {
		ResultEnum
	} from "@/enums/httpEnum";
	import {
		Path,
		getTableColumns,
		getTableData
	} from "@/api/modules/table";
	import {
		getCheckingInTableHeader,getCheckingInMonthTableDetailData,getLocationSelect
	} from "@/api/modules/personalManagementApi/checkingIn";
	import { getDictOptions} from "@/api/modules/sysManage/personnel";
	import { getLocationParams } from "@/utils/index";
	import useDateFormat from "@/hooks/useDateFormat";
	const format = useDateFormat().renderFormat("YYYY-MM");
	const { proxy } = getCurrentInstance()!;
	//import dateHead from "@/assets/json/dateHead.json";
	//import dateData from "@/assets/json/dateMsg.json";
	
	const org_id=ref("")
	const nodeChange = (menuItem) =>{
		state.thisPageDate.org_id = menuItem.org_id;
		
		const newUrl = new URL(window.location.href);
		//console.log(newUrl)
		newUrl.searchParams.set('org_id', menuItem.org_id);
		org_id.value= menuItem.org_id;
		// 使用pushState更新浏览器历史记录
		window.history.pushState({}, '', newUrl.toString());
		
		state.thisPageDate.org_id = menuItem.org_id;
	}
	const convertSecondsToHMS = (seconds)=> {
	  var hours = Math.floor(seconds / 3600);
	  var minutes = Math.floor((seconds % 3600) / 60);
	  var remainingSeconds = seconds % 60;
	  if(hours > 0){
		 return hours + proxy!.$t("clockingIn_daily.hour") + minutes + proxy!.$t("clockingIn_daily.minute") + remainingSeconds + proxy!.$t("clockingIn_daily.second"); 
	  } else {
		  if(minutes > 0){
			  let timemsg = minutes + proxy!.$t("clockingIn_daily.minute");
			  if(remainingSeconds > 0){
				  timemsg += remainingSeconds + proxy!.$t("clockingIn_daily.second");
			  }
			  return timemsg
		  } else {
			  return remainingSeconds + proxy!.$t("clockingIn_daily.second");
		  }
	  }
	}
	const formattedTime = (timestamp) => {
		let date = new Date(parseInt(timestamp) * 1000);
		let Year = date.getFullYear();
		let Moth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
		let Hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
		let Minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
		let Sechond = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
		let GMT =  Hour +':'+ Minute  + ':' + Sechond;
		return GMT;
	}
	
	const formattedDay = (timestamp) => {
		let date = new Date(parseInt(timestamp) * 1000);
		let Year = date.getFullYear();
		let Moth = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
		let Day = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
		let Hour = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours());
		let Minute = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes());
		let Sechond = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
		let  GMT =  Year + '-' + Moth + '-' + Day + '   '+ Hour +':'+ Minute  + ':' + Sechond;
		return GMT;
	}
	const formattedDate = () => {
		const today = new Date();
		let year = today.getFullYear();
		let month = (today.getMonth() + 1).toString().padStart(2, '0');
		return `${year}-${month}`;
	}
	
	const editDate = () =>{
		queryColumns()
	}
	// 使用队列 loading 管理初始化页面加载状态
	const {
		queueLoading,
		queueId
	} = useLoading();
	const pageData = reactive({
		menuList: [] //全部菜单
	});
	const page_parents_id = ref("");
	// 页面配置数据
	const state = reactive < {
		filterOptions: Array < any > ;
		statValue: string;
		statData: MerakStatDataType[][];
		statParams: Record < string,string > ;
		thisPageDate : Record < string,string > ;
	} > ({
		// 高级搜索方案下拉选项
		filterOptions: [],
		// 统计筛选激活项
		statValue: "",
		// 统计筛选数据
		statData: [],
		// 统计筛选激活后筛选数据
		statParams: {},
		thisPageDate:{
			date:formattedDate(),
			org_id:"0",
			keyword:"",
			office_location_id:'',
		},
	});

	// 动态计算表格的外部筛选数据
	const params = computed(() => ({
		...state.statParams,
		...state.thisPageDate
	}));

	// 表格配置属性
	const tablePayload = reactive < MerakXTableProps > ({
		//动态表头数据
		columns: [],
		toolbar: ["export"],
		border:true,
		enabledExport:false,
		// 列设置存储的数据对照值
		columnsByStore: [],
		// 表格行数据的唯一 key, 跟后端同步
		rowKey: "user_id",
		rowHeight:70,
		config:{},
		// 初始化的外部筛选数据
		params
	});

	/**
	 * 表格批量操作事件触发
	 * @param type 同 tablePayload.batched 子项的 type
	 * @param mode 表格选中的模式  current: 当前页  all: 所有页
	 * @param selectedKeys 表格当前页选中模式下选中的行数据 key 的集合, 表格所有页选中模式下未选中的行数据 key 的集合
	 */
	const handleBatchClick: MerakXTableInstance["batchClick"] = async ({
		type,
		mode,
		selectedKeys
	}) => {
		switch (type) {
			case "delete":
				return {
					// 是否刷新表格, 默认 false, 可选参数
					refresh: false,
						// 是否重置表格(分页、排序), 默认 false, 可选参数
						reset: false
				};
			default:
				return;
		}
	};

	/**
	 * 表格操作列事件触发
	 * @param type 同 tablePayload.handles 子项的 type
	 * @param params 表格操作数据, 可结构关于操作行的数据 { row, rowIndex, rowId }
	 */
	const handleHanderClick: MerakXTableInstance["handlerClick"] = async ({
		type,
		params
	}) => {
		switch (type) {
			case "delete":
				// 是否刷新表格, 默认 false, 可选参数
				return true;
			default:
				return;
		}
	};
	// 获取表头数据
	const queryColumns: MerakXTableInstance["queryColumns"] = async () => {
		let columnsData = {
			type:'MonthStatisticsDetail'
		}
		if(state.thisPageDate.date != ''){
			columnsData.date = state.thisPageDate.date
		}
		// 初始化接口需要传入队列 loading 暴露的 id
		return getCheckingInTableHeader(columnsData).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				// 克隆表头数据作为列设置的对照数据
				const columns = data.columns as MerakXTableColumn[];
				tablePayload.columnsByStore = JSON.parse(JSON.stringify(columns));
				tablePayload.config = {table_id:data.table_id,version:data.version}
				columns[0].fixed = "left";
				columns.map((colimnsItem, colimnsIndex) => {
					colimnsItem.headerAlign = "center";
					if (colimnsItem.field == "employee_name") {
						colimnsItem.slots = {
							//header:"employee_details_head",
							default: "employee_details"
						};
					}

					if (colimnsIndex == 0) {
						colimnsItem.fixed = "left";
						colimnsItem.width = "140px";
					} else {
						colimnsItem.width = "140px";
					}
					if (!!colimnsItem.params?.isDay) {
						colimnsItem.slots = {
							header: ({
								column
							}) => {
								let dayValue = column.params.day;
								let weekValue = column.params.week;
								return <div><div>{dayValue}</div><div>{weekValue}</div></div>
							},
							default:"day_box"
							
						};

					}
				});
				tablePayload.columns = columns;
			}
		});
	};

	/**
	 * 获取表格数据
	 * @param page 分页参数
	 * @param sorts 多重排序参数
	 * @param filters 表头筛选参数
	 * @param from 外部由 tablePayload.params 传入的自定义参数
	 */
	const queryData: MerakXTableInstance["queryData"] = async ({
		page,
		sorts,
		from
	}) => {
		// 创建请求表格数据的参数
		const params: Record < string, any > = {};
		// 如果有分页数据
		if (!!page) {
			Object.assign(params, {
				...page
			});
		}
		// 如果有排序数据
		if (!!sorts) {
			for (let sort of sorts.values()) {
				console.log(sort);
			}
		}
		// 如果有自定义参数
		if (!!from) {
			for (let key of Object.keys(from)) {
				const item = from[key];
				!!item && (params[key] = item);
			}
		}
		// 初始化接口需要传入队列 loading 暴露的 id
		return getCheckingInMonthTableDetailData(params).then(({
			code,
			data
		}) => {
			if (code == ResultEnum.SUCCESS) {
				return data.table_data;
			}
		});
	};
	
	//工作地点数组
	const workLocationArr = ref([]);
	const getWorkLocation = () => {
		getLocationSelect().then(({ code, data }) => {
		  if (code == 2000) {
				data.map(e=>{
					e.label = e.value;
					e.value = e.key;
				})
				workLocationArr.value = data;
		  }
		});
	}
	// 初始化页面
	const init = async () => {
		queryColumns();
		getWorkLocation()
	};

	// 监听初始化队列 loading 状态
	watch(queueLoading, () => {
		if (queueLoading.value) {
			// 页面初始化队列 loading 时不允许 table 自动 loading
			tablePayload.loading = false;
		} else if ("loading" in tablePayload) {
			// 队列 loading 完成后清除 table 受控的 loading 属性
			delete tablePayload.loading;
		}
	});

	// 运行初始化
	onMounted(() =>{
		
		const newUrl = new URL(window.location.href);
		let url_org_id = getLocationParams(newUrl.href,'org_id');
		if(url_org_id !== false){
			org_id.value=url_org_id;
			state.thisPageDate.org_id = url_org_id;
		}
		
		 init()
	});
	//触发了快速搜索或者搜索方案
	const searchBarPost = params => {
		//console.log(params)
		let postParams = {
			...params.params,
		};
		state.thisPageDate.keyword = params.search;
	};
	const goDetailPage = tableRows =>{
		router.push({path:'/clockingIn/person',query:{id:tableRows.user_id}})
	}
</script>

<style lang="scss" scoped>
	@import "./index.scss";
</style>
<style lang="scss" >
	.clockingInTable .vxe-table.vxe-table--render-default .vxe-table--render-wrapper .vxe-table--header-wrapper .vxe-header--row .vxe-header--column{
		height: 60px !important;
	}
</style>